#include "StdAfx.h"
#include "IMLogic.h"
#include "MIMDef.h"
#include "util/string_convert.h"
#include "IMClient.h"
#include "IBuddylist.h"
#include "AccountInfoMgr.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

CIMLogic	*CIMLogic::s_Instance = NULL;

CIMLogic::CIMLogic(void)
:m_pClient(NULL)
,m_pUISinker(NULL)
{
}

CIMLogic::~CIMLogic(void)
{
	if (m_pClient)
	{
		delete m_pClient;
		m_pClient = NULL;
	}
}

CIMLogic *CIMLogic::GetInstance()
{
	if (!s_Instance)
	{
		s_Instance = new CIMLogic;
		_ASSERTE(s_Instance);
	}

	return s_Instance;
}

void CIMLogic::ReleaseInstance()
{
	if (s_Instance)
	{
		delete s_Instance;
		s_Instance = NULL;
	}
}

void CIMLogic::SetUISinker(CUISinker	*pUISinker)
{

	if (m_pUISinker != pUISinker)
	{
		m_pUISinker = pUISinker;
	}
}

HRESULT CIMLogic::LoginOn(TCHAR *szAccount,TCHAR *szPassword,int nStatus)
{
	CString strAccount = szAccount,strPassword = szPassword;
	if (strAccount.IsEmpty()|| strPassword.IsEmpty())
	{
		_ASSERTE(FALSE);

		return E_FAIL;
	}

	if (!InitClient())
	{
		return E_FAIL;
	}

	USES_UTF8_CONVERSION;
	CAccountInfoMgr::GetInstance()->SetAccountName(szAccount);
	CAccountInfoMgr::GetInstance()->SetPassword(szPassword);

	if (0 != m_pClient->SignIn(T2UTF8(strAccount),T2UTF8(strPassword),MIM::Status::ssAvailable,MIMClient::Protocol::kGtalk))
	{
		_ASSERTE(FALSE);

		return E_FAIL;
	}

	return S_OK;
}

HRESULT CIMLogic::LoginOff()
{
	if (m_pClient)
	{
		m_pClient->SignOut();
	}

	return S_OK;
}

void CIMLogic::SendMsg(TCHAR *szTo,TCHAR *szMsg)
{
	if (m_pClient)
	{
		m_pClient->SendMsg(szTo,szMsg);
	}
}

void CIMLogic::SendFile(TCHAR *szTo,TCHAR *szFilePath)
{
	if (m_pClient)
	{
		m_pClient->SendFile(szTo,szFilePath);
	}

}

BOOL CIMLogic::InitClient()
{
	if (m_pClient)
	{
		delete m_pClient;
		m_pClient = NULL;
	}
	m_pClient = new CIMClient(this);
	if (!m_pClient)
	{
		_ASSERTE(FALSE);

		return FALSE;
	}

	return TRUE;
}

void CIMLogic::SetLoginReponse(int nResult)
{
	if (m_pUISinker)
	{
		m_pUISinker->OnLoginStatusChange(nResult);
	}

}

void CIMLogic::AddBuddyInfo(TCHAR *szAccount,TCHAR *szNick,TCHAR *szGroup,int nStaus)
{
	IBuddylist *pBuddylist = NULL;
	CAccountInfoMgr::GetInstance()->GetBuddylist(&pBuddylist);

	BUDDY_INFO bi;
	bi.strAccoutName = szAccount;
	bi.strNick = szNick;
	bi.strGroup = szGroup;
	bi.nStatus =nStaus;

	pBuddylist->AddItem(bi);

	m_pUISinker->OnUpdateBuddyList();

}

void CIMLogic::OnNewMessage(TCHAR *szFrom,TCHAR *szMsg)
{
	m_pUISinker->OnNewMessage(szFrom,szMsg);
}

void CIMLogic::OnRecvFileRequest(TCHAR *szFrom,TCHAR *szFile)
{
	if (m_pUISinker)
	{
		m_pUISinker->OnRecvFileRequest(szFrom,szFile);
	}
	
}